package net.adetech.web.utils;

import net.adetech.utils.UtilsCommon;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by sunfeihu on 2016/10/14.
 */
public class UtilsHttp {

    private static Logger logger = LoggerFactory.getLogger(UtilsHttp.class);

    public static String doPost(String url, String content) throws IOException {
        String htmRs = "";
        return htmRs;
    }

    public static String doGet(String url) throws IOException {
        return doGet(url, null);
    }


    public static String doGet(String url, javax.servlet.http.Cookie[] cookies) throws IOException {
        String htmRs = "";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Request.Builder result = request.newBuilder();
        client.cookieJar().loadForRequest(request.url());
        if (null != cookies && cookies.length > 0) {
            result.header("Cookie", cookieHeader(cookies));
        }
        Call call = client.newCall(request);
        Response response = call.execute();
        if (response.code() == 200) {
            htmRs = response.body().string();
        } else {
            logger.warn(response.code() + "");
        }
        return htmRs;
    }

    private static String cookieHeader(javax.servlet.http.Cookie[] cookies) {
        StringBuilder cookieHeader = new StringBuilder();
        for (int i = 0, size = cookies.length; i < size; i++) {
            if (i > 0) {
                cookieHeader.append("; ");
            }
            javax.servlet.http.Cookie cookie = cookies[i];
            cookieHeader.append(cookie.getName()).append('=').append(cookie.getValue());
        }
        return cookieHeader.toString();
    }

    public static void createCookie(HttpServletResponse response, String key, String value, int time) {
        javax.servlet.http.Cookie cookie = null;
        try {
            value = URLEncoder.encode(value, "utf-8");
            cookie = new javax.servlet.http.Cookie(key, value);
            cookie.setMaxAge(time);
            cookie.setPath("/");
            response.addCookie(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cookie = null;
        }
    }

    public static String doPost(String url, Map<String, String> params) throws IOException {
        return doPost(url, params, null);
    }

    public static String doPost(String url, Map<String, String> params, javax.servlet.http.Cookie[] cookies) throws IOException {
        String htmRs = "";
        FormBody.Builder builder = new FormBody.Builder();
        if (null != params && params.size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, UtilsCommon.getString(params.get(key)));
            }
        }
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Request.Builder result = request.newBuilder();
        client.cookieJar().loadForRequest(request.url());
        if (null != cookies && cookies.length > 0) {
            result.header("Cookie", cookieHeader(cookies));
        }
        Call call = client.newCall(request);
        Response response = call.execute();
        if (response.code() == 200) {
            htmRs = response.body().string();
        } else {
            logger.warn(response.code() + "");
        }
        return htmRs;
    }

    public static void doPostHttpAsync(String url, Map<String, String> params) throws Exception {
        doPostHttpAsync(url, params, null);
    }

    public static void doPostHttpAsync(String url, Map<String, String> params, Cookie[] cookies) throws Exception {

    }

}
